package com.ruoyi.patient.service;

import com.ruoyi.patient.entity.LoginPatient;
import com.ruoyi.patient.entity.PatientServedVO;
import com.ruoyi.patient.entity.ServedBody;
import com.ruoyi.patient.entity.ServedRequest;
import com.ruoyi.patient.utils.SendSmsUtil;
import com.ruoyi.service.domain.ServiceAddress;
import com.ruoyi.service.domain.ServicePhonecode;
import com.ruoyi.service.domain.ServiceServed;
import com.ruoyi.service.mapper.ServiceAddressMapper;
import com.ruoyi.service.mapper.ServiceAppinfoMapper;
import com.ruoyi.service.mapper.ServicePhonecodeMapper;
import com.ruoyi.service.mapper.ServiceServedMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.util.*;


@Component
public class ServedService {

    @Autowired
    private ServiceServedMapper servedMapper;

    @Autowired
    private ServiceAddressMapper addressMapper;

    @Autowired
    private ServiceAppinfoMapper appinfoMapper;

    @Autowired
    private ServicePhonecodeMapper phonecodeMapper;

    @Qualifier("patientRestTemplate")
    @Autowired
    private RestTemplate restTemplate;


    @Transactional
    public boolean addServed(ServedRequest servedRequest, LoginPatient oldPatient)
    {
        try {
            List<PatientServedVO> oldServed = getServed(oldPatient);
            ServiceServed servedBody = new ServiceServed();
            servedBody.setServedName(URLDecoder.decode( servedRequest.getName(), "UTF-8" ));
            servedBody.setServedIdnumber(servedRequest.getIdCard());
            servedBody.setServedTelephonenumber(servedRequest.getPhone());
            if ("男".equals(servedRequest.getGender())){
                servedBody.setServedSex("0");
            }else if ("女".equals(servedRequest.getGender())){
                servedBody.setServedSex("1");
            }else{
                servedBody.setServedSex("0");
            }
            servedBody.setServedConnect(URLDecoder.decode( servedRequest.getRelation(), "UTF-8" ));
            servedBody.setServedVisitid(servedRequest.getEpidNo());
            servedBody.setServedUserid(oldPatient.getUserId());
            servedBody.setServedUpdateBy(oldPatient.getUsername());
            servedBody.setServedCreateBy(oldPatient.getUsername());
            servedBody.setServedCreateTime(new Date());
            servedBody.setServedUpdateTime(new Date());
            if(oldServed.size() == 0){
                servedBody.setServedDefaultFlag("0");
            }

            ServiceAddress newAddress = new ServiceAddress();
            newAddress.setAddressUserid(oldPatient.getUserId());
            newAddress.setAddressInfo(URLDecoder.decode( servedRequest.getAddress(), "UTF-8" ));
            newAddress.setAddressPeople(URLDecoder.decode( servedRequest.getName(), "UTF-8" ));
            newAddress.setAddressPhone(servedRequest.getPhone());
            newAddress.setAddressCreateBy(oldPatient.getUsername());
            newAddress.setAddressCreateTime(new Date());
            newAddress.setAddressUpdateBy(oldPatient.getUsername());
            newAddress.setAddressUpdateTime(new Date());

            if (servedRequest.getServeId() == null){
                addressMapper.insertServiceAddress(newAddress);
                servedBody.setServedAddress(newAddress.getAddressId());
                servedMapper.insertServiceServed(servedBody);
            }else {
                ServiceServed served = servedMapper.selectServiceServedByServedId(servedRequest.getServeId());
                newAddress.setAddressId(served.getServedAddress());
                addressMapper.updateServiceAddress(newAddress);
                servedBody.setServedId(servedRequest.getServeId());
                servedMapper.updateServiceServed(servedBody);
            }

        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Transactional
    public boolean updateServed(ServiceServed servedBody, LoginPatient oldPatient)
    {
        try {
            servedBody.setServedUseFlag("2");
            servedBody.setServedDelFlag("2");
            servedBody.setServedUpdateBy(oldPatient.getUsername());
            servedBody.setServedUpdateTime(new Date());
            servedMapper.updateServiceServed(servedBody);

            if ("0".equals(servedBody.getServedDefaultFlag())){
                ServiceServed searchServed = new ServiceServed();
                searchServed.setServedUserid(oldPatient.getUserId());
                searchServed.setServedDefaultFlag("2");
                searchServed.setServedUseFlag("0");
                searchServed.setServedDelFlag("0");
                List<ServiceServed> oldServedList = servedMapper.selectServiceServedList(searchServed);
                if (oldServedList.size() > 0){
                    ServiceServed oldServed = oldServedList.get(0);
                    oldServed.setServedDefaultFlag("0");
                    servedMapper.updateServiceServed(oldServed);
                }
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    public List<PatientServedVO> getServed(LoginPatient oldPatient)
    {
        ServedBody searchSerced = new ServedBody();
        searchSerced.setServedUserid(oldPatient.getUserId());
        searchSerced.setServedUseFlag("0");
        searchSerced.setServedDelFlag("0");
        List<ServiceServed> retServedList = servedMapper.selectServiceServedList(searchSerced);
        List<PatientServedVO> patientServedVO = new ArrayList<PatientServedVO>();
        for(ServiceServed served:retServedList){
            PatientServedVO servedVO = new PatientServedVO(served);
            ServiceAddress address = addressMapper.selectServiceAddressByAddressId(served.getServedAddress());
            //servedVO.setServedAddress(address.getAddressInfo() + ":" + address.getAddressDetail());
            servedVO.setServedAddress(address.getAddressInfo());
            patientServedVO.add(servedVO);
        }

        return patientServedVO;
    }

    /**
     * 根据身份证号计算年龄
     * @param servedIdnumber
     * @return
     */
    public Integer getPersonAgeFromIdCard(String servedIdnumber) {

        //截取身份证中出行人出生日期中的年、月、日
        Integer personYear = Integer.parseInt(servedIdnumber.substring(6, 10));
        Integer personMonth = Integer.parseInt(servedIdnumber.substring(10, 12));
        Integer personDay = Integer.parseInt(servedIdnumber.substring(12, 14));

        Calendar cal = Calendar.getInstance();
        // 得到当前时间的年、月、日
        Integer yearNow = cal.get(Calendar.YEAR);
        Integer monthNow = cal.get(Calendar.MONTH) + 1;
        Integer dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        Integer yearMinus = yearNow - personYear;
        Integer monthMinus = monthNow - personMonth;
        Integer dayMinus = dayNow - personDay;

        Integer age = yearMinus; //先大致赋值

        if (yearMinus == 0) { //出生年份为当前年份 
            age = 0;
        }else{ //出生年份大于当前年份
            if (monthMinus < 0) {//出生月份小于当前月份时，还没满周岁
                age = age - 1;
            }
            if (monthMinus == 0) {//当前月份为出生月份时，判断日期
                if (dayMinus < 0) {//出生日期小于当前月份时，没满周岁
                    age = age - 1;
                }
            }
        }
        return age;
    }

    @Transactional
    public Boolean sendCode(String phone, LoginPatient oldPatient) throws NoSuchFieldException {
        //ServiceAppinfo appinfo = appinfoMapper.selectServiceAppinfoByAppinfoId(3L);
        ////String requestUrl = "https://192.168.2.7/qyHosApi/rest/sms/sendCode";
        //String requestUrl = "https://hlwyy.ldqyylzx.cn/qyHosApi/rest/sms/sendCode";
        //Map<String, String> requestUrlParam = new HashMap<>();
        //
        //requestUrlParam.put("phone", phone);
        //
        //requestUrlParam.put("type", "1");
        //
        //requestUrlParam.put("orgCode", appinfo.getAppinfoOrgcode());
        //HttpHeaders headers = new HttpHeaders();
        //HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(requestUrlParam, headers);
        //System.out.println(httpEntity);
        //ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, httpEntity, Object.class);
        //String body = String.valueOf(response.getBody());// 解析JSON字符串

        Random randObj = new Random();
        String code = Integer.toString(100000 + randObj.nextInt(900000));

        Boolean result = SendSmsUtil.sendSMS(phone, code);
        if (result){
            ServicePhonecode phonecode = new ServicePhonecode();
            phonecode.setPhonecodeCode(code);
            phonecode.setPhonecodePhone(phone);
            phonecode.setPhonecodeUserid(oldPatient.getUserId());

            //时间+5分钟
            Date currentDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.MINUTE, 5);
            Date futureDate = calendar.getTime();

            phonecode.setPhonecodeTime(futureDate);
            phonecodeMapper.insertServicePhonecode(phonecode);
        }

        return result;
    }

    @Transactional
    public Integer verifyCode(String code, String phone, LoginPatient oldPatient) throws NoSuchFieldException {
        //ServiceAppinfo appinfo = appinfoMapper.selectServiceAppinfoByAppinfoId(3L);
        ////String requestUrl = "https://192.168.2.7/qyHosApi/rest/sms/verifyCode";
        //String requestUrl = "https://hlwyy.ldqyylzx.cn/qyHosApi/rest/sms/verifyCode";
        //Map<String, String> requestUrlParam = new HashMap<>();
        //
        //requestUrlParam.put("phone", phone);
        //
        //requestUrlParam.put("code", code);
        //
        //requestUrlParam.put("orgCode", appinfo.getAppinfoOrgcode());
        //HttpHeaders headers = new HttpHeaders();
        //HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(requestUrlParam, headers);
        //System.out.println(httpEntity);
        //ResponseEntity<Object> response = restTemplate.postForEntity(requestUrl, httpEntity, Object.class);
        //String body = String.valueOf(response.getBody());// 解析JSON字符串
        //Pattern pattern = Pattern.compile("code=(\\d+)");
        //Matcher matcher = pattern.matcher(body);
        //if (matcher.find()) {
        //    //String group = matcher.group(1);
        //    Boolean result = "200".equals(matcher.group(1)) ? true : false; // 获取括号中的数字
        //    return result;
        //}else {
        //    return false;
        //}

        ServicePhonecode searchBody = new ServicePhonecode();
        searchBody.setPhonecodeUserid(oldPatient.getUserId());
        searchBody.setPhonecodePhone(phone);
        searchBody.setPhonecodeCode(code);

        List<ServicePhonecode> phonecodes = phonecodeMapper.selectServicePhonecodeList(searchBody);
        if (phonecodes.size() > 0){
            ServicePhonecode phonecode = phonecodes.get(0);
            if (phonecode.getPhonecodeTime().getTime() < new Date().getTime()){
                phonecodeMapper.deleteServicePhonecodeByPhonecodeId(phonecode.getPhonecodeId());
                return 2;
            }
            phonecodeMapper.deleteServicePhonecodeByPhonecodeId(phonecode.getPhonecodeId());
            return 0;
        }

        return 1;
    }
    
    
}
